package com.tianhao.luo.readwrite;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 锁降级
 *
 * @author tianhao.luo@hand-china.com
 */
public class ReadWriteLockDemo3 {
    public static void main(String[] args) {
        // 锁降级
        //demotion();

        // 锁升级，错误操作
        //upgrade();
    }

    /**
     * 锁升级
     *
     * 注意这个操作是错误的
     */
    public static void upgrade(){
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

        // 模拟锁升级
        readLock.lock();
        System.out.println("read");
        writeLock.lock();
        System.out.println("lock");
        writeLock.unlock();
        readLock.unlock();

    }

    /**
     * 写锁降级为读锁
     */
    public static void demotion(){
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

        // 开始锁降级：写锁可以降级为读锁
        writeLock.lock();
        System.out.println("lock");
        readLock.lock();
        System.out.println("read");
        readLock.unlock();
        writeLock.unlock();
    }
}
